package com.kaifamiao.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

/**
 * 通过传统IO获得 Channel 的方法:
 *    Channels:
 *       static ReadableByteChannel	newChannel(InputStream in)
 *       static WritableByteChannel	newChannel(OutputStream out)
 *    FileInputStream:
 *       FileChannel getChannel()
 *    FileOutputStream:
 *       FileChannel getChannel()
 *    RandomAccessFile:
 *       FileChannel getChannel()
 *    ...
 * 我们主张使用 java.nio.file.Files 提供的支持获得 Channel
 */
public class ChannelTest {

    public static void main(String[] args) throws IOException {
        Path path = Path.of("files-and-streams", "src/com/kaifamiao/nio/ChannelTest.java");
        if( Files.exists(path) ) {

            final ByteBuffer buffer = ByteBuffer.allocate(32);

            // 创建只读通道(Channel)
            ByteChannel channel = Files.newByteChannel( path, StandardOpenOption.READ );

            final byte[] bytes = new byte[32];

            int n;
            // 通过通道将数据读取到字节缓冲区中并返回实际读取到的字节数
            while( ( n = channel.read( buffer ) ) != -1 ) {
                buffer.flip();
                // 将 buffer 中的 [0, n ) 之间的数据读取 bytes 数组中
                buffer.get(bytes, 0, n);
                // 将 bytes 数组中 [0, n) 之间的字节序列构造成字符串
                String s = new String(bytes, 0, n, StandardCharsets.UTF_8);
                System.out.print(s);
                buffer.clear();
            }

            // 关闭通道
            channel.close();
        }
    }

}
